<?php
/**
 *      [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.haidao.la
 *      tel:400-600-2042
 */
class notify_service extends service
{
	protected $entrydir = '';

	public function _initialize() {
		$this->entrydir = MODULE_PATH.'library/driver/';
		$this->table = model('notify');
	}

	public function fetch_all() {
		$folders = glob($this->entrydir.'*');
        foreach ($folders as $key => $folder) {
            $file = $folder. DIRECTORY_SEPARATOR .'config.xml';
            if(file_exists($file)) {
                $importtxt = @implode('', file($file));
                $xmldata = xml2array($importtxt);
                $notifys[$xmldata['code']] = $xmldata;
            }
        }
        $notifys = array_merge_multi($notifys, $this->get_fech_all());
		return $notifys;
	}

	/* 根据标识 */
	public function fetch_by_code($code) {
		if(empty($code)) {
			$this->error = '参数错误';
			return false;
		}
		if(!is_dir($this->entrydir.$code) || !file_exists($this->entrydir.$code)) {
			$this->error = '没有找到驱动配置文件';
			return false;
		}
		$config = $this->entrydir.$code.'/config.xml';
        $importtxt = @implode('', file($config));
        $xmldata = xml2array($importtxt);
        return $xmldata;
	}

	public function config($vars, $code) {
		$notify = $this->fetch_by_code($code);
		if($notify === false) {
			return false;
		}
		$notify['config'] = json_encode($vars);
		if($this->table->find($code)) {
			$rs = $this->table->update($notify);
		} else {
			$rs = $this->table->add($notify);
			model('notify_template')->add(array('id'=>$code));
		}
		if($rs === false) {
			$this->error = '配置操作失败';
			return false;
		}
		$this->get_fech_enable_code();
		return true;
	}

	public function get_fech_all() {
		$result = array();
		$notifys = model('notify')->getField('code,enabled,config', TRUE);
		foreach ($notifys as $key => $value) {
			$value['configs'] = json_decode($value['config'], TRUE);
			$result[$value['code']] = $value;
		}
		return $result;
	}
	
	//根据code获取启用的通知方式
	public function get_fech_enable_code($code) {
		$result = cache('notify_enable');
		if(FALSE === $result || empty($code)){
			$result = array();
			$notifys = model('notify')->where(array('enabled'=>1))->getField('code,enabled,config', TRUE);
			foreach ($notifys as $key => $value) {
				$value['configs'] = json_decode($value['config'], TRUE);
				$result[$value['code']] = $value;
			}
			cache('notify_enable',$result);
			$result = cache('notify_enable');
		}
		return $result[$code];
	}
	
	/**
	 * [启用禁用支付方式]
	 * @param string $pay_code 支付方式标识
	 * @return TRUE OR ERROR
	 */
	public function change_enabled($code) {
		$result = $this->table->where(array('code' => $code))->save(array('enabled' => array('exp', '1-enabled'), 'dateline' => time()));
		if ($result == 1) {
			$result = TRUE;
			$this->get_fech_enable_code();
		} else {
			$result = $this->table->getError();
		}
		return $result;
	}

	/**
	 * 通知执行接口
	 * $hook 钩子名
	 * $data 数据array
	 * $level 优先级
	 * $execution 是否立即执行
	 */
	public function execute($hook,$data,$level=100,$execution=TRUE){
		$hook_data = model('notify/notify_template','service')->fetch_by_hook($hook);
		$unit = new unit();
		foreach($hook_data as $k=>$v){
			switch($v['id']){
				//$to, $sender, $subject, $body, $mailtype
				case 'email':
					$template = $v['template'];
					$email_title = str_replace(array_keys($data), $data, $template['title']);
					$email_content = str_replace(array_keys($data), $data, $template['content']);
				
					$email['to'] =  $data['to'];
					$email['subject'] = $email_content;
					$email['body'] = $email_content;
					$email['mailtype'] = $data['mailtype'];

					$params['type'] = 'email';
					$params['method'] = 'send';
					$params['sort'] = $level;
					$params['dateline'] = time();
					$params['params'] = $unit->array2json($email);
					
					if(!in_array('', $email)){
						model('notify/queue','service')->add($params);
					}
					//model('notify/queue', 'service')->config('email')->send($email);
					break;
				//	$mid, $title, $message, $dateline;	
				case 'message':
					$template = $v['template'];
					$message_title = str_replace(array_keys($data), $data, $template['title']);
					$message_content = str_replace(array_keys($data), $data, $template['content']);
					
					$message['mid'] =  $data['mid'];
					$message['title'] = $message_content;
					$message['message'] = $message_content;
					
					$params['type'] = 'message';
					$params['method'] = 'send';
					$params['sort'] = $level;
					$params['dateline'] = time();
					$params['params'] = $unit->array2json($message);
					
					if(!in_array('', $message)){
						model('notify/queue','service')->add($params);
					}
					
					//model('notify/queue', 'service')->config('message')->send($message);
					break;
				//$mobile, $tpl_id, $sms_sign, tpl_vars(array)
				case 'sms':
					$sms['mobile'] = $data['mobile'];
					$sms['tpl_id'] = $v['template']['template_id'];
					$sms['tpl_vars'] = $this->format_sms_data($data);
					
					$params['type'] = 'sms';
					$params['method'] = 'send';
					$params['sort'] = $level;
					$params['dateline'] = time();
					$params['params'] = $unit->array2json($sms);
					
					if(!in_array('', $sms)){
						model('notify/queue','service')->add($params);
					}
					
					//model('notify/queue', 'service')->config('sms')->send($sms);
					break;
				//根据微信模板
				case 'wechat':
					$wechat['touser'] = $data['touser'];
					$wechat['template_id'] = $v['template']['template_id'];
					$wechat['url'] = $data['url'];
					$wechat['data'] = $data['data'];
					
					
					$params['type'] = 'wechat';
					$params['method'] = 'send';
					$params['sort'] = $level;
					$params['dateline'] = time();
					$params['params'] = $unit->array2json($wechat);

					if(!in_array('', $wechat)){
						model('notify/queue','service')->add($params);
					}
					break;
			}
		}
		if($execution){
			$url='http://'.$_SERVER['SERVER_NAME'].url('notify/queue/index');
			dfsockopen($url);
		}
		return TRUE;
	}
	public function format_sms_data($data){
		foreach ($data as $k => $v) {
			if(preg_match('/\{(.+?)\}/', $k)){
				$_data[preg_replace('/\{(.+?)\}/','$1',$k)] = $v;
			}
		}
		return $_data;
	}
}